/*
 * pit.c
 *
 *  Created on: Apr 8, 2013
 *      Author: Vincent
 */


#include "support_common.h"
#include <stdio.h>
#include "pit0.h"
#include "intc.h"
#include "ledmat.h"
#include "n_chuck.h"

int chuck_flag=0;
int chuck_flag2=0;
int chuck_read_flag;

void pit0_init()
{
        MCF_PIT0_PCSR = 0x00; //EN cleared to set things
        MCF_PIT0_PCSR |= 0x0E00; // prescaler to 14
        MCF_PIT0_PCSR |= 0x20; //DBG enabled
        MCF_PIT0_PCSR |= 0x10; //OVW enabled
        MCF_PIT0_PCSR |= 0x08; //PIE enabled
        MCF_PIT0_PCSR |= 0x04; //PIF enabled
        MCF_PIT0_PCSR |= 0x02; //RLD
        MCF_PIT0_PMR  = 5; // needs to change with delays
        int_uninhibit_all(); // uninhibit interrupts at all levels
        int_config(55,4,6,pit0_isr);
        
}

asm __declspec(standard_abi) void int_inhibit_all()
{
	 move.w SR, d0  //This is a supervisor mode instruction
	 ori.l #0x0700, d0  //Write 111 to bits 10:8
	 move.w d0, SR  //SR[I] <- 111
	 rts
}

asm __declspec(standard_abi) void int_uninhibit_all()
{
        move.w SR, d0
        andi.l #0xF8FF, d0
        move.w d0, SR
        rts
}

void pit0_enable()
{
	MCF_PIT0_PCSR |= 0x0001;
}

void pit0_disable() 
{
	//clear PCSR0[0] EN bit
	MCF_PIT0_PCSR &= ~(0x0001);
}

__declspec(interrupt) void pit0_isr()
{
       
        /* Clear the PIF channel 0 interrupt request flag. */
        MCF_PIT0_PCSR |= 0x4;
        //pit0_disable();
        flag = 1;
     //   ledmat_refresh();
        if (all_flag >= 20)
        { all_flag =0;     
        }
        else 
        {all_flag = all_flag+1;}
        
       
        if (chuck_flag<=60)
        {
        	chuck_flag = chuck_flag+1;
        }
        else if (chuck_flag2==0 && chuck_flag>60)
        {
        	n_chuck_read ();
        	chuck_flag=0;
        }
      
}
